<template>
	<view class="container">
		<Loading v-show="showLoading" />

		<view class="wrapper" v-if="!showLoading">

			<view class="name-list">
				<view class="name-item" v-for="name in nameList">
					<text>
						{{name}}
					</text>
					<view class="add-cart" @click="addToStorage(name)">
						加入备选
					</view>
				</view>
			</view>


			<button class="re-generate" :class="{'btn-disabled':showLoading}" @click="reGenerate"> 重新生成 </button>

		</view>
	</view>
</template>

<script>
	import Loading from '@/components/Loading.vue'
	import {
		toast
	} from '../../uni_modules/uv-ui-tools/libs/function'
	export default {
		data() {
			return {
				showLoading: false,
				prompt: "",
				nameList: [],
				localNames: []
			}
		},
		components: {
			Loading
		},
		onLoad(option) {
			console.log("收到参数：", option)
			this.prompt = option


			this.sendMessage()

			// 从本地存储读取姓名列表
			this.localNames = uni.getStorageSync("local-name") || []
		},
		methods: {
			async sendMessage() {
				this.showLoading = true;

				const res = await uniCloud.callFunction({
					name: "bq-uniai",
					data: {
						prompt: this.prompt
					}
				})
				this.showLoading = false;

				console.log(res)

				let reply = res.result?.reply;
				this.nameList.unshift(reply)


			},
			// 重新生成
			reGenerate() {

				this.sendMessage()

			},
			addToStorage(name) {

				if (this.localNames.includes(name)) {
					return
				}

				this.localNames.unshift(name)
				uni.setStorageSync("local-name", this.localNames)

				toast("成功！在我的页面可以查看")

			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		height: 100%;
		padding-bottom: 162rpx;
		background-color: #dedede;
		overflow-y: scroll;
	}

	.wrapper {
		padding: 20rpx;
		padding-bottom: 162rpx;


		.name-list {
			font-size: 36rpx;

			.name-item {
				min-height: 100px;
				border-radius: 20rpx;
				box-sizing: border-box;
				padding: 20rpx;
				background-color: #fff;
				margin-bottom: 20rpx;
				padding-bottom: 100rpx;
				position: relative;

				.add-cart {
					background-color: red;
					color: #fff;
					text-align: center;
					padding: 12rpx 24rpx;
					border-radius: 40rpx;
					position: absolute;
					right: 20rpx;
					bottom: 20rpx;
				}
			}
		}
	}

	.re-generate {
		width: 90vw;
		background-color: red;
		color: #fff;
		font-size: 40rpx;
		position: fixed;
		bottom: 48rpx;

	}

	.btn-disabled {
		background-color: #999;
	}
</style>